package com.ansion.commonchat.startup.workmanager.bwork.impl;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ansion.commonchat.startup.workmanager.bwork.BOperation;
import com.ansion.commonchat.startup.workmanager.bwork.utils.futures.BSettableFuture;
import com.google.common.util.concurrent.ListenableFuture;

/**
 * Created by wanghongjie on 2023/5/5
 * Describe : OperationImpl 是 WorkManager 内部用于执行和管理异步操作的关键组件，
 * 它提供了一种可靠且可扩展的方式来处理工作请求，并确保操作在适当的时机被执行和完成
 */
public class BOperationImpl implements BOperation {

    private final MutableLiveData<State> mOperationState;
    private final BSettableFuture<State.SUCCESS> mOperationFuture;

    public BOperationImpl() {
        mOperationState = new MutableLiveData<>();
        mOperationFuture = BSettableFuture.create();
        setState(BOperation.IN_PROGRESS);
    }

    @Override
    public @NonNull
    ListenableFuture<State.SUCCESS> getResult() {
        return mOperationFuture;
    }

    @Override
    public @NonNull
    LiveData<State> getState() {
        return mOperationState;
    }

    public void setState(@NonNull State state) {
        mOperationState.postValue(state);

        if (state instanceof State.SUCCESS) {
            mOperationFuture.set((State.SUCCESS) state);
        } else if (state instanceof State.FAILURE) {
            State.FAILURE failed = (State.FAILURE) state;
            mOperationFuture.setException(failed.getThrowable());
        }
    }
}